<template>
  <div class="redpacket-container">
    <!-- 头部区域 -->
    <header class="redpacket-header">
      <div class="header-content">
        <img :src="user.userImg" alt="用户头像" class="user-avatar">
        <div class="user-info">
          <h3 class="user-id">{{ user.userId }}</h3>
          <p class="user-name">{{ user.userName }}</p>
        </div>
      </div>
      <h1 class="page-title">我的红包</h1>
    </header>

    <!-- 红包列表区域 -->
    <main class="redpacket-content">
      <!-- 筛选按钮 -->
      <div class="filter-buttons">
        <button
            :class="['filter-btn', {active: status===0}]"
            @click="getRedPackets(0)"
        >
          全部
        </button>
        <button
            :class="['filter-btn', {active: status===1}]"
            @click="getRedPackets(1)"
        >
          可用
        </button>
        <button
            :class="['filter-btn', {active: status===2}]"
            @click="getRedPackets(2)"
        >
          已用
        </button>
      </div>

      <!-- 红包列表 -->
      <div class="redpacket-list">
        <div
            v-for="item in redPacketArr"
            :key="item.redPacketId"
            :class="['redpacket-card', {used: item.used}]"
        >
          <div class="card-main" @click="detailetShow(item)">
            <div class="amount-info">
              <span class="amount">{{redPacketToken(item.amount)}}{{item.amount}}元</span>
              <span class="time">{{formatDate(item.createTime)}}</span>
            </div>
            <i
                :class="['toggle-icon', item.isShowDetailet ? 'fa fa-angle-up' : 'fa fa-angle-down']"
            ></i>
          </div>

          <!-- 红包详情 -->
          <div v-show="item.isShowDetailet" class="card-detail">
            <div class="detail-row">
              <span class="label">红包ID：</span>
              <span class="value">{{item.id}}</span>
            </div>
            <div class="detail-row">
              <span class="label">状态：</span>
              <span :class="['status', {used: item.used}]">
                {{redPacketStatus(item.used)}}
              </span>
            </div>
            <div v-if="item.orderId" class="detail-row">
              <span class="label">关联订单：</span>
              <span class="value">{{item.orderId}}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页控制 -->
      <div class="pagination">
        <button
            class="page-btn prev"
            @click="pageChange(-1)"
            :disabled="pageNow === 1"
        >
          <i class="fa fa-chevron-left"></i> 上一页
        </button>
        <span class="page-indicator">第 {{pageNow}} 页</span>
        <button
            class="page-btn next"
            @click="pageChange(1)"
            :disabled="redPacketArr.length < 8"
        >
          下一页 <i class="fa fa-chevron-right"></i>
        </button>
      </div>

      <!-- 兑换红包按钮 -->
      <button class="exchange-btn" @click="showExchangeModal = true">
        <i class="fa fa-gift"></i> 兑换红包
      </button>
    </main>

    <!-- 兑换红包弹窗 -->
    <div v-if="showExchangeModal" class="modal-overlay" @click.self="showExchangeModal = false">
      <div class="exchange-modal">
        <div class="modal-header">
          <h3>兑换红包</h3>
          <i class="fa fa-times close-btn" @click="showExchangeModal = false"></i>
        </div>
        <div class="modal-body">
          <div class="select-wrapper">
            <select v-model="selectedOption" class="redpacket-select">
              <option disabled value="">请选择红包面额</option>
              <option value="3">3元红包</option>
              <option value="5">5元红包</option>
              <option value="10">10元红包</option>
            </select>
            <i class="fa fa-chevron-down select-arrow"></i>
          </div>
        </div>
        <div class="modal-footer">
          <button
              class="submit-btn"
              @click="handleSubmit"
              :disabled="!selectedOption"
          >
            确认兑换
          </button>
        </div>
      </div>
    </div>

    <!-- 底部菜单部分 -->
    <Footer></Footer>
  </div>
</template>

<script>
import { ref, onMounted, getCurrentInstance } from 'vue';
import Footer from '../components/Footer.vue';
import axios from 'axios';
import qs from 'qs';

export default {
  name: 'RedPacket',
  setup() {
    const selectedOption = ref('');
    const showExchangeModal = ref(false);
    const user = ref({});
    const redPacketArr = ref([]);
    const pageNow = ref(1);
    const status = ref(0);
    const { proxy } = getCurrentInstance();

    // 日期格式化
    const formatDate = (dateString) => {
      const date = new Date(dateString);
      return `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    };

    // 提交按钮的处理逻辑
    const handleSubmit = async() => {
      if (selectedOption.value) {
        const response = await axios.get("/CreditController/consumeCredit", {
          params:{
            userId:user.value.userId,
            channelId:2,
            eventId:selectedOption.value
          }
        });
        if(response.data==1){
          alert("兑换红包成功");
          window.location.reload();
        } else{
          alert("积分不足");
        }
      } else {
        alert('请选择一个选项');
      }
    };

    // 红包状态转换
    const redPacketStatus = (status) => {
      const statusMap = {
        false: "未使用",
        true: "已使用"
      };
      return statusMap[status] || "未知状态";
    };

    // 金额符号
    const redPacketToken = (amount) => {
      return amount > 0 ? "+" : "";
    };

    // 获取红包列表
    const getRedPackets = async (operation) => {
      if(status.value!=operation){
        pageNow.value=1;
      }
      status.value = operation;
      let url = "";
      switch (operation) {
        case 0:
          url = `CreditController/listAllRedPackets/${user.value.userId}/${pageNow.value}/8`;
          break;
        case 1:
          url = `CreditController/listAvailableRedPackets/${user.value.userId}/${pageNow.value}/8`;
          break;
        case 2:
          url = `CreditController/listUsedRedPackets/${user.value.userId}/${pageNow.value}/8`;
          break;
      }
      try {
        const response = await axios.get(url);
        let result = response.data;
        result.forEach(packet => {
          packet.isShowDetailet = false;
        });
        redPacketArr.value = result;
      } catch (error) {
        console.error(error);
      }
    };

    onMounted(() => {
      user.value = proxy.$getSessionStorage('user');
      pageNow.value = 1;
      getRedPackets(0);
    });

    // 显示/隐藏详情
    const detailetShow = (packet) => {
      packet.isShowDetailet = !packet.isShowDetailet;
    };

    const pageChange = (isNext) => {
      if(pageNow.value==1&&isNext==-1){
        alert("已经是第一页");
        return;
      }
      if(redPacketArr.value.length<8&&isNext==1){
        alert("没有更多内容了");
        return;
      }
      pageNow.value+=isNext;
      console.log(pageNow.value);
      getRedPackets(status.value);
    }

    return {
      user,
      redPacketArr,
      status,
      pageNow,
      selectedOption,
      showExchangeModal,
      redPacketStatus,
      redPacketToken,
      formatDate,
      getRedPackets,
      detailetShow,
      pageChange,
      handleSubmit
    };
  },
  components: {
    Footer
  }
};
</script>

<style scoped>
/* 基础样式 */
.redpacket-container {
  font-family: 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;
  max-width: 100%;
  background-color: #f8f8f8;
  min-height: 100vh;
  padding-bottom: 60px; /* 为底部导航留出空间 */
  position: relative;
  box-sizing: border-box;
}

/* 头部样式 */
.redpacket-header {
  background: linear-gradient(135deg, #ff4e4e, #cc3e3e);
  color: white;
  padding: 15px;
  position: relative;
}

.header-content {
  display: flex;
  align-items: center;
}

.user-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  border: 2px solid rgba(255, 255, 255, 0.3);
  object-fit: cover;
}

.user-info {
  margin-left: 12px;
}

.user-id {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 2px;
}

.user-name {
  font-size: 14px;
  opacity: 0.9;
}

.page-title {
  font-size: 22px;
  font-weight: 600;
  text-align: center;
  margin-top: 15px;
  margin-bottom: 5px;
}

/* 内容区域 */
.redpacket-content {
  padding: 15px;
  padding-bottom: 80px; /* 增加底部内边距，防止内容被底部导航遮挡 */
}

/* 筛选按钮 */
.filter-buttons {
  display: flex;
  justify-content: center;
  gap: 10px;
  margin-bottom: 20px;
}

.filter-btn {
  padding: 8px 16px;
  border: 1px solid #ff4e4e;
  background: transparent;
  color: #ff4e4e;
  border-radius: 20px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}

.filter-btn.active {
  background: #ff4e4e;
  color: white;
}

.filter-btn:hover {
  background: #ff7b7b;
  color: white;
}

/* 红包卡片 */
.redpacket-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-bottom: 20px;
}

.redpacket-card {
  background: white;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  transition: all 0.3s;
}

.redpacket-card.used {
  opacity: 0.7;
}

.card-main {
  padding: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
}

.amount-info {
  display: flex;
  flex-direction: column;
}

.amount {
  font-size: 18px;
  font-weight: bold;
  color: #ff4e4e;
  margin-bottom: 5px;
}

.redpacket-card.used .amount {
  color: #999;
}

.time {
  font-size: 13px;
  color: #999;
}

.toggle-icon {
  color: #ccc;
  font-size: 18px;
  transition: transform 0.3s;
}

/* 红包详情 */
.card-detail {
  padding: 0 15px 15px;
  border-top: 1px solid #f0f0f0;
  margin-top: 10px;
}

.detail-row {
  display: flex;
  margin-bottom: 8px;
  font-size: 14px;
}

.label {
  color: #666;
  min-width: 70px;
}

.value {
  color: #333;
}

.status {
  color: #4caf50;
  font-weight: 500;
}

.status.used {
  color: #999;
}

/* 分页控制 */
.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 25px 0;
  gap: 15px;
}

.page-btn {
  padding: 8px 15px;
  border: 1px solid #ddd;
  background: white;
  border-radius: 20px;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 14px;
}

.page-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-btn:hover:not(:disabled) {
  border-color: #ff4e4e;
  color: #ff4e4e;
}

.page-indicator {
  font-size: 14px;
  color: #666;
}

/* 兑换红包按钮 */
.exchange-btn {
  display: block;
  width: 100%;
  padding: 12px;
  background: linear-gradient(135deg, #ff4e4e, #ff7b7b);
  color: white;
  border: none;
  border-radius: 25px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  box-shadow: 0 4px 12px rgba(255, 78, 78, 0.3);
  transition: all 0.3s;
  margin-top: 20px;
}

.exchange-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(255, 78, 78, 0.4);
}

/* 兑换红包弹窗 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.exchange-modal {
  background: white;
  border-radius: 15px;
  width: 85%;
  max-width: 400px;
  overflow: hidden;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
  animation: modalFadeIn 0.3s;
}

@keyframes modalFadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.modal-header {
  padding: 15px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  font-size: 18px;
  color: #333;
}

.close-btn {
  color: #999;
  font-size: 18px;
  cursor: pointer;
}

.modal-body {
  padding: 20px 15px;
}

.select-wrapper {
  position: relative;
}

.redpacket-select {
  width: 100%;
  padding: 12px 15px;
  border: 1px solid #ddd;
  border-radius: 8px;
  appearance: none;
  font-size: 15px;
  background-color: white;
}

.select-arrow {
  position: absolute;
  right: 15px;
  top: 50%;
  transform: translateY(-50%);
  color: #999;
  pointer-events: none;
}

.modal-footer {
  padding: 15px;
  border-top: 1px solid #f0f0f0;
  text-align: right;
}

.submit-btn {
  padding: 10px 25px;
  background: #ff4e4e;
  color: white;
  border: none;
  border-radius: 20px;
  font-size: 15px;
  cursor: pointer;
  transition: all 0.3s;
}

.submit-btn:hover {
  background: #ff7b7b;
}

.submit-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}
/* 底部菜单样式 */
.footer {
  width: 100%;
  height: 5vw;
  border-top: solid 1px #DDD;
  background-color: #fff;
  position: fixed;
  left: 0;
  bottom: 0;
  display: flex;
  justify-content: space-around;
  align-items: center;
  list-style: none;
  margin: 0;
  padding: 0;
}
</style>